package jsr166.contrib.uncontended;
import java.util.Iterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

/**
 * 
 */

class ReadWriteLockedIterator<E, C extends Iterator<E>> implements Iterator<E> {
    final C base;
    final ReadWriteLock rwLock;
    final Lock lock;
    public ReadWriteLockedIterator(C base, ReadWriteLock rwLock) {
        this.base = base;
        this.rwLock = rwLock;
        if (rwLock instanceof UncontendedReadWriteLock)
            lock = new UncontendedLock();
        else lock = new NoOpUncontendedLock();
    }
    public boolean hasNext() {
        rwLock.readLock().lock();
        try {
        lock.lock();
        try {
             return base.hasNext();
        } finally {
            lock.lock();
        } } finally {
            rwLock.readLock().unlock();
        }
    }

    public E next() {
        rwLock.readLock().lock();
        try {
        lock.lock();
        try {
             return base.next();
        } finally {
            lock.unlock(); 
        }} finally {
            rwLock.readLock().unlock();
        }
    }

    public void remove() {
        rwLock.writeLock().lock();
        try {
        lock.lock();
        try {
              base.remove();
        } finally {
            lock.unlock();
        }} finally {
            rwLock.writeLock().unlock();
        }
        
    }
    
}